/*
 * realtime_timer.h
 *
 * Copyright 2011 Pieter Agten
 *
 * This file is part of Yarf.
 *
 * Yarf is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Yarf is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Yarf.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file   realtime_timer.h
 * @author Pieter Agten (pieter.agten@gmail.com)
 * @date   9 okt 2011
 * @brief  The real-time timer is a high resolution, high priority timer which
 *         is used for controlling the rate at which the stepper motors are
 *         stepped.
 */

#ifndef REALTIME_TIMER_H_
#define REALTIME_TIMER_H_

#include <stdint.h>

/**
 * The number of ticks the real-time timer takes in one minute.
 */
#define RTTIMER_TICKS_PER_MIN (F_CPU/8L*60L)

/**
 * 'Success' return value.
 */
#define RTTIMER_SUCCESS      0
/**
 * 'Busy' return value.
 */
#define RTTIMER_BUSY        -1
/**
 * 'Not running' return value.
 */
#define RTTIMER_NOT_RUNNING -2

/**
 * Structure for tasks that can be scheduled with the real-time timer.
 */
typedef struct {
  void (*f)(void); /**< @brief Pointer to the function to execute when the timer rings */
  uint16_t ticks_remaining; /**< @brief Number of ticks remaining before the timer must ring */
} realtime_task_t;


/**
 * Initializes the real-time timer component.
 *
 * This should only be called once on boot.
 */
void rttimer_init(void);

/**
 * Schedules a task to be executed after a specified number of ticks.
 *
 * @param t pointer to the task to be executed
 * @param ticks the number of ticks to wait before executing the task
 * @return \a RTTIMER_SUCCESS on success or \a RTTIMER_BUSY if the timer already
 *         has a scheduled task to be executed. 
 */
int rttimer_schedule_ticks(realtime_task_t *t, uint16_t ticks);

/**
 * Cancels the currently scheduled task.
 *
 * @return \a RTTIMER_SUCCESS on success or \a RTTIMER_NOT_RUNNING if the timer
 *         does not currently have any task scheduled.
 */
int rttimer_cancel(void);


#endif //REALTIME_TIMER_H_
